#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <unistd.h>
#include <time.h>
#include "dht.h"

//initialize the vairables
struct sockaddr_in this_client_info;
struct sockaddr_in dht_node_info;
int this_node_port_num;
int root_node_port;
int bytes_recieved;
int this_client_socket;

char send_data[1024],recv_data[1024];
char root_node_ip[64];


int main(int argc, char *argv[]){
  if (argc !=2) {
    //taking in node ip & port num
    printf("Usage: \n %s <dhtnode>\n", argv[0]);
    
  } else {
    //initializing node_input and pointer node_in
    char node_input[64];
    char *node_in;
	  
    strncpy(node_input, argv[1], 64-1);
		
    //seperatly reading what's in front of the :
    node_in = strtok(node_input, ":");
    
    if(node_in)
	    {//read in the IP
	      strncpy(root_node_ip, node_in, 64-1);
	      printf("Root Node IP\t: %s\n", root_node_ip);
	    }
    
    //read what's behind the :
    node_in = strtok(NULL, ":");
	  
    if(node_in) {// read in the port number
      root_node_port = atoi(node_in);
      printf("Root Node Port\t: %i\n", root_node_port);
    }
    
    char * s = malloc(3);
    //ping has an ID 4, thus sending 4
    memcpy(s, "4|", 2);
    
    //connecting
    node_connect(root_node_ip,root_node_port, s);
  }
  
}


int node_connect(int dst_ip[64], int dst_port, char send_data[512]){
  //creating socket using TCP
  if ((this_client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
    //if error, display error
    perror("Socket Error");
    exit(EXIT_FAILURE);
  }
  
  //setting up the connection
  this_client_info.sin_family = AF_INET; 
  inet_aton(dst_ip, &(this_client_info.sin_addr)); 
  this_client_info.sin_port = htons(dst_port);
  bzero(&(this_client_info.sin_zero), 8);
  printf("connected...\n");
  
  if (connect(this_client_socket, (struct sockaddr *)&this_client_info,
	      sizeof(struct sockaddr)) == -1)
    {
      perror("Connect Error\t");
      exit(1);
    }
  
  //sending the data over then closing the connection
  send(this_client_socket,send_data,strlen(send_data), 0);   
  //close(this_client_socket);
  
  while(1)
     {
       
       bytes_recieved=recv(this_client_socket,recv_data,1024,0);
       recv_data[bytes_recieved] = '\0';
       
       if (bytes_recieved > 0) {
	 printf("\nthe node is alive = %s\n" , recv_data);
	 printf("recv_data is : %s\n", recv_data);
	 close(this_client_socket);
	 
	 //printf("\nSEND (q or Q to quit) : ");
	 fflush(stdout);
	 break;
       }       

       return 0;
       
       
     }
  
}


